﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using MazeRunner.Graphics;
using OpenTK.Input;
using MazeRunner.GameState;

namespace MazeRunner.GameLogic
{
	class MainGameForm : GameWindow
	{
		private GameCore gameCore;
		private Matrix4d projection;

		public MainGameForm() : base(640, 480)
		{
			this.Mouse.ButtonDown += new EventHandler<OpenTK.Input.MouseButtonEventArgs>(Mouse_ButtonDown);
			this.Mouse.ButtonUp += new EventHandler<OpenTK.Input.MouseButtonEventArgs>(Mouse_ButtonUp);
			this.Mouse.Move += new EventHandler<OpenTK.Input.MouseMoveEventArgs>(Mouse_Move);

			gameCore = new GameCore();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			OpenGLSetup.InitializeOpenGL(640, 480);
			projection = Matrix4d.CreatePerspectiveFieldOfView((float)(Math.PI / 4), 640.0f/480.0f, 1.0, 64.0);
		}

		protected override void OnRenderFrame(FrameEventArgs e)
		{
			base.OnRenderFrame(e);
			GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

			GL.LoadMatrix(ref projection);
			GL.Rotate(gameCore.XRot, 0, 1.0, 0);
			GL.Translate(gameCore.CameraPos * -1);
			//Matrix4 view = Matrix4.LookAt(gameCore.CameraPos, gameCore.CameraView, Vector3.UnitY);
			//GL.MultMatrix(ref view);

			gameCore.Draw();

			SwapBuffers();
		}

		protected override void OnUpdateFrame(FrameEventArgs e)
		{
			base.OnUpdateFrame(e);
			if (Keyboard[Key.Escape])
			{
				Exit();
			}
			gameCore.Update(this, e);
		}

		void Mouse_Move(object sender, MouseMoveEventArgs e)
		{
			gameCore.MouseMove(e);
		}

		void Mouse_ButtonUp(object sender, OpenTK.Input.MouseButtonEventArgs e)
		{

		}

		void Mouse_ButtonDown(object sender, OpenTK.Input.MouseButtonEventArgs e)
		{
			
		}
	}
}
